package com.itbaiyun.usercenter.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itbaiyun.usercenter.common.BaseResponse;
import com.itbaiyun.usercenter.common.ErrorCode;
import com.itbaiyun.usercenter.common.ResultUtil;
import com.itbaiyun.usercenter.exception.BusinessException;
import com.itbaiyun.usercenter.mapper.UserMapper;
import com.itbaiyun.usercenter.model.domain.User;
import com.itbaiyun.usercenter.model.dto.UserSearchDto;
import com.itbaiyun.usercenter.request.UserLoginRequest;
import com.itbaiyun.usercenter.request.UserRegisterRequest;
import com.itbaiyun.usercenter.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.itbaiyun.usercenter.constant.RedisConstant.*;
import static com.itbaiyun.usercenter.constant.UserConstant.USER_LOGIN_STATE;

/**
 * 用户接口
 */
@RestController
@CrossOrigin(origins = {"http://localhost:8000"})
@Slf4j
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserMapper userMapper;

    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 用户注册
     *
     * @param userRegisterRequest
     * @return
     */
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {

        if (userRegisterRequest == null) {
//            return ResultUtil.error(ErrorCode.PARAMS_NULL_ERROR);
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        String planetCode = userRegisterRequest.getPlanetCode();
        //对参数做校验
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            return ResultUtil.error(ErrorCode.PARAMS_NULL_ERROR);
        }

        long result = userService.UserRegister(userAccount, userPassword, checkPassword, planetCode);
        return ResultUtil.sucess(result);
    }

    /**
     * 用户登录
     *
     * @param userLoginRequest
     * @param request
     * @return
     */
    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {

        if (userLoginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_NULL_ERROR);
        }

        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        //对参数做校验
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_NULL_ERROR);
        }

        User user = userService.userLogin(userAccount, userPassword, request);
        return ResultUtil.sucess(user);
    }

    /**
     * 用户注销
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public BaseResponse<Integer> userLogout(HttpServletRequest request) {
        if (request == null) {
            return null;
        }
        int result = userService.UserLogout(request);
        return ResultUtil.sucess(result);

    }

    /**
     * 查看用户状态
     *
     * @param request
     * @return
     */
    @GetMapping("/current")
    public BaseResponse<User> getCurrentUSer(HttpServletRequest request) {
        User userObj = (User) request.getSession().getAttribute(USER_LOGIN_STATE);
        if (userObj == null) {
            return null;
        }
        long userId = userObj.getId();
        User user = userService.getById(userId);
        User safetyUser = userService.getSafetyUser(user);
        return ResultUtil.sucess(safetyUser);
    }

    /**
     * 分页搜索用户
     * 仅管理员可查,能查出用户完整信息
     * @param
     * @param request request
     * @return 返回搜索结果
     */
    @GetMapping("/searchPage")
    public BaseResponse<Page<User>> searchUsersPage(UserSearchDto userSearchDto, HttpServletRequest request) {
//        //鉴权  仅管理员可查询
//        if (!userService.isAdmin(request)) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR);
//        }
//        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//        if (StringUtils.isNotBlank(username)) {
//            queryWrapper.like("username", username);
//        }
//        List<User> list = userService.list(queryWrapper);
//        List<User> result = list.stream().map(user -> userService.getSafetyUser(user)).collect(Collectors.toList());
//        return ResultUtil.sucess(result);

        //仅管理员可查
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
//        String userAccount = userSearchDto.getUserAccount();
//        String username = userSearchDto.getUsername();
        User user = new User();
        BeanUtils.copyProperties(userSearchDto,user);
        Page<User> userPage = new Page<>(userSearchDto.getPageNum(), userSearchDto.getPageSize());
        QueryWrapper<User> queryWrapper = new QueryWrapper<>(user);
//        //组装查询条件
//        if (userAccount != null) {
//            queryWrapper.like("userAccount", userAccount);
//        }
//        if (username != null) {
//            queryWrapper.like("username", username);
//        }
        Page<User> page = userMapper.searchUserByPage(userPage, queryWrapper,userSearchDto);
        return ResultUtil.sucess(page);
    }
    /**
     * 搜索用户
     *
     * @param
     * @param request request
     * @return 返回搜索结果
     */
    @GetMapping("/search")
    public BaseResponse<List<User>> searchUsers(String username, HttpServletRequest request) {
        //鉴权  仅管理员可查询
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(username)) {
            queryWrapper.like("username", username);
        }
        List<User> list = userService.list(queryWrapper);
        List<User> result = list.stream().map(user -> userService.getSafetyUser(user)).collect(Collectors.toList());
        return ResultUtil.sucess(result);
    }

    /**
     * 根据标签搜索用户
     *
     * @param tagList 标签列表
     * @return 返回搜索结果
     */
    @GetMapping("/search/tags")
    public BaseResponse<List<User>> searchUsersByTags(List<String> tagList) {
        //参数判断
        if (CollectionUtils.isEmpty(tagList)) {
            throw new BusinessException(ErrorCode.PARAMS_NULL_ERROR, "参数为空");
        }
        List<User> list = userService.searchUserByTags(tagList);
        return ResultUtil.sucess(list);
    }

    /**
     * 删除用户接口,remove方法会自动的转换为逻辑删除
     *
     * @param id 被删除的用户id
     * @return 返回删除结果
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUsers(@RequestBody long id, HttpServletRequest request) {
        if (!userService.isAdmin(request)) {
            return null;
        }
        //id不能为空
        if (id <= 0) {
            return null;
        }
        boolean b = userService.removeById(id);
        return ResultUtil.sucess(b);
    }

    /**
     * 更新用户信息
     *
     * @param user    更新的用户信息
     * @param request request
     * @return 更新结果
     */
    @PostMapping("/update")
    public BaseResponse<Integer> updateUser(User user, HttpServletRequest request) {
        //1.校验参数是否为空
        if (user == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        //2.校验权限,非本用户或者不是管理员不能修改
        if (user.getId() != loginUser.getId() || !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        //3.触发更新
        Integer result = userService.updateUser(user, loginUser);
        return ResultUtil.sucess(result);
    }

    /**
     * 用户更换头像
     *
     * @param request 用户登录状态
     * @return 返回更换结果
     */
    @PostMapping("/changeAvatar")
    public BaseResponse<Boolean> changeAvatar(HttpServletRequest request, String avatarUrl, User user) {
        User loginUser = userService.getLoginUser(request);
        //判空
        if (StringUtils.isBlank(avatarUrl)) {
            throw new BusinessException(ErrorCode.PARAMS_NULL_ERROR, "头像不能为空!");
        }
        //权限校验
        //未登录不能更换头像
        if (ObjectUtils.isEmpty(request)) {
            throw new BusinessException(ErrorCode.NO_LOGIN);
        }
        //仅管理员和本用户可更换头像
        if (!userService.isAdmin(loginUser) || loginUser.getId() != user.getId()) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        boolean result = userService.changeAvatar(user, avatarUrl);
        return ResultUtil.sucess(result);
    }

    /**
     * 推荐用户
     */
    @GetMapping("/recommend")
    public BaseResponse<Page<User>> recommmendUser(HttpServletRequest request, long pageSize, long pageNum) {
        //获取登录用户
        User loginUser = userService.getLoginUser(request);
        //设置缓存key
        String key = String.format(RECOMMEND_USER_KET + ":%s", loginUser.getId());
        //从缓存中获取数据
        //如果缓存中存在数据,则直接返回
        Page<User> userPage = (Page<User>) redisTemplate.opsForValue().get(key);
        if (userPage != null) {
            return ResultUtil.sucess(userPage);
        }
        //如果为空,则查询数据库
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        userPage = userService.page(new Page<>(pageNum, pageSize), queryWrapper);
        //解决缓存穿透
        //如果查出的数据为null 则返回一个空
        if (userPage == null) {
            redisTemplate.opsForValue().set(key, "", RECOMMEND_USER_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        //如果有数据,将查出的结果写入缓存--.设置过期时间
        try {
            redisTemplate.opsForValue().set(key, userPage, RECOMMEND_USER_TTL, TimeUnit.SECONDS);
        } catch (Exception e) {
            log.error("写入缓存失败:", e);
        }

        return ResultUtil.sucess(userPage);

    }
}
